package com.uyayo.framework.captcha.util;

import com.uyayo.framework.captcha.constants.CaptchaConstants;
import com.uyayo.framework.captcha.exception.CaptchaException;
import com.uyayo.framework.captcha.exception.CaptchaTimeOutException;

/**
 * 滑块验证码
 * @author hfj
 * @date 2019/5/20
 */
public class SliderCaptchaUtils {

    /**
     * 检查文字点击验证码
     * @param x           x轴坐标值
     * @param sx    session中保存的x轴坐标值
     * @return 是否验证成功
     */
    public static boolean checkSliderCaptcha(String x,String sx){

        double imagePointX = Double.parseDouble(sx);
        double maxRange = imagePointX + 2;
        double minRange = imagePointX - 2;
        double realPointX = Double.parseDouble(x);
        return realPointX > minRange && realPointX < maxRange;
    }


    /**
     * 验证码校验
     * 默认验证码超时时间 10 分钟
     *
     * @param x           x轴坐标值
     * @param sx    session中保存的x轴坐标值
     * @param captchaTimeObject 验证码记录的时间
     * @throws CaptchaTimeOutException 验证码超时
     * @throws CaptchaException        验证码错误
     */
    public static void verifySliderCaptcha(String x,String sx, Object captchaTimeObject) throws CaptchaException {
        verifySliderCaptcha(x, sx, captchaTimeObject, CaptchaConstants.CAPTCHA_TIMEOUT);
    }

    /**
     * 验证码校验
     * 默认验证码超时时间 10 分钟
     *
     * @param x           x轴坐标值
     * @param sx    session中保存的x轴坐标值
     * @param captchaTimeObject 验证码记录的时间
     * @param timeOut           验证码超时时间 毫秒
     * @throws CaptchaTimeOutException 验证码超时
     * @throws CaptchaException        验证码错误
     */
    public static void verifySliderCaptcha(String x,String sx, Object captchaTimeObject, long timeOut) throws CaptchaException {
        if (null == sx || null == captchaTimeObject) {
            throw new CaptchaException("Captcha is null");
        }
        long captchaTime = (Long) captchaTimeObject;
        if (System.currentTimeMillis() - captchaTime > timeOut) {
            throw new CaptchaTimeOutException("captcha timeout");
        }

        boolean result = SliderCaptchaUtils.checkSliderCaptcha(x, sx);
        if(!result){
            throw new CaptchaException("captcha exitCode error");
        }
    }
}
